package project.houseRent.service;

import project.houseRent.domain.House;

/**
 * 具体的业务逻辑实现
 */
public class HouseService {
    //初始化房屋列表
    private House[] houses;

    public HouseService(int length){
        this.houses = new House[length+1];
    }


    /**
     * 创建房屋
     * @param house
     */
    public boolean createHouse(House house) {
        //新增的房屋超过了数组的容量，那要考虑扩容数组（一次扩容20）
        //扩容之前
        boolean flag = false; //判断是否正常添加
        //下标和id保持一致
        for (int i = 1; i < houses.length; i++) {
            if(houses[i]==null){
                houses[i]=house;
                flag = true;
                break;
            }
        }
        if(flag){
            return true;
        }
        //进行数组扩容
        houses = expandHouses(houses);
        for (int i = 1; i < houses.length; i++) {
            if(houses[i]==null){
                houses[i]=house;
                flag = true;
                break;
            }
        }
        if(flag){
            return true;
        }
        System.out.println("----------添加失败-------------");
        return false;
    }

    /**
     * 根据id查找房屋信息
     * @param findId
     * @return
     */

    public House findById(int findId) {
        //防止数组越界
        if(findId>=houses.length){
            return null;
        }
        if(houses[findId] == null){
            return null;
        }
        return houses[findId];
    }

    /**
     * 通过id删除房屋
     * @param delId
     */

    public void deleteHouse(int delId) {
        if(delId>=houses.length || houses[delId]==null || delId <= 0){
            //本来就不存在这样的房屋，直接删除完成
            System.out.println("------------删除完成-------------");
        }
        if(houses[delId] != null){
            houses[delId]=null;
            System.out.println("------------删除完成-------------");
        }
    }

    public void updateHouse(House house2) {
        int id = house2.getId();
        houses[id]=house2;
    }

    public void list() {
        System.out.println("------------房屋列表------------");
        System.out.println("编号\t\t房主\t\t电话\t\t地址\t\t月租\t\t状态(未出租/已出租)");
        for (int i = 1; i < houses.length; i++) {
            if(houses[i]!=null){
                System.out.println(houses[i]);
            }
        }
        System.out.println("------------房屋列表完成------------");
    }

    /**
     * ============================封装类============================
     */

    /**
     * 功能：扩容数组
     * 获取当前需要扩容的数组，每次调用本方法就扩容20
     */
    public House[] expandHouses(House[] houses) {
       House[] newHouses =  new House[houses.length+20];
        for (int i = 0; i < houses.length; i++) {
            newHouses[i] = houses[i];
        }
        return newHouses;
    }
}
